package com.seculab.admin.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtil {
	private static final Logger logger = Logger.getLogger(FileUploadUtil.class);
	
	public static void uploadFile(MultipartFile formFile, String realPath) throws Exception {
        UUID uuid = UUID.randomUUID();
        String tempFileName = uuid.toString();
        OutputStream bos = null;
        InputStream stream = null;

        try {
            stream = formFile.getInputStream();

            bos = new FileOutputStream(realPath + tempFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("The file has been written to \"" + realPath
                        + tempFileName);
            }
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
        	throw e;
        } finally {
            bos.close();
            stream.close();
        }
    }
}
